<template>
  <section class="w3l-hotair-form">
    <h1>软件缺陷定位工具</h1>
    <div class="container">
      <div class="workinghny-form-grid">
        <div class="main-hotair">
          <div class="content-wthree">
            <h2>Log In</h2>
            <form action="#" @submit.prevent="userLogin" method="post">
              <input
                  type="text"
                  v-model="param.username"
                  class="username" name="username"
                  placeholder="username" required autofocus
              />
              <input
                  type="password"
                  v-model="param.password"
                  class="password"
                  name="password"
                  placeholder="password"
                  required autofocus
              />
              <button class="btn" type="submit"  >Login</button>
            </form>
            <p class="account">Don't have an account? <a href="#" @click.prevent="userRegister" >Register</a></p>
          </div>
          <div class="w3l_form align-self">
            <div class="left_grid_info">
              <img src="../../assets/img/login-aside.png" alt="" class="img-fluid" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="copyright text-center">
      <p class="copy-footer-29">© 2024 Written By Cosine. All Rights Reserved</p>
    </div>
  </section>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useTabsStore } from '@/store/tabs';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import axios from 'axios';

interface LoginInfo {
    username: string;
    password: string;
}

const lgStr = localStorage.getItem('login-param');

const defParam = lgStr ? JSON.parse(lgStr) : null;

const globalApiUrl = import.meta.env.VITE_API_URL

console.log('Global API URL:', globalApiUrl);

const loginUrl =  globalApiUrl + '/login';

const router = useRouter();
const param = reactive<LoginInfo>({
    username: defParam ? defParam.username : '',
    password: defParam ? defParam.password : '',
});

const userLogin = (formEl: FormInstance | undefined) => {

    if (!formEl) return;

    console.log(loginUrl);
    axios.post(loginUrl, {
        username: param.username,
        password: param.password,
    })
    .then((response) => {
        console.log(response.data);
        if (response.data.result) {

            // 登录成功弹出消息
            ElMessage({
                message: "登录成功",
                type: 'success',
                plain: true,
            });

            const token = response.data.data.access_token;  // 假设后端返回的是 access_token
            localStorage.setItem('access_token', token);  // 存储 JWT Token
            console.log(token);


            // 跳转到主页
            setTimeout(() => {
                router.push('/');
            }, 500);
        } else {
            // 登录失败弹出消息
            ElMessage({
                message: response.data.message,
                type: 'error',
                plain: true,
            });
        }
    })
    .catch((error) => {
        // 处理请求错误
        ElMessage({
            message: "请求错误，请稍后再试",
            type: 'error',
            plain: true,
        });
        console.error("Login error:", error);
    });
};

const userRegister = () => {
    router.push('/register');
};


const tabs = useTabsStore();
tabs.clearTabs();
</script>

<style>
@import url("//fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@400;500;700;900&display=swap");
@import "./../../assets/css/style.css";
@import "./../../assets/css/font-awesome.min.css";
</style>